checkLogin();

scorllInit();

var originalData = {
    data: {
        goods_list: {
            data: getCartList(),
            next_page_url: '',
        }
    }
}

$("#store_name").html(getCache(login_key).shop_name);

function scorllInit() {
    var info = getScreen();
    var footer_height = parseInt($(".nctouch-cart-bottom").height());
    var header_height = 0;
    if (is_local || is_weixn()) {
        header_height = parseInt($(".mui-bar").height());
    }
    if(isNaN(header_height)){
        header_height = 0;
    }
    var cart_store_height = parseInt($(".nctouch-cart-store").height());
    var scroll_height = info[1] - footer_height - header_height - cart_store_height + 'px';
    fenye_options.scrollHeight = scroll_height; //设置分页滚轴高度（自适应）
    mui('.mui-control-content').each(function () {
        this.style.height = scroll_height;
    });
    mui('.mui-scroll-wrapper').each(function (k, v) {
        mui(v).scroll({
            deceleration: (mui.os.ios ? 0.003 : 0.0006),
            indicators: false  //隐藏一条滚动条 增大减速系数。。。
        });
    });
}
mui.init({
    pullRefresh: {
        container: fenye_options.scrollNode,//待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
        up: {
            height: 50,//可选.默认50.触发上拉加载拖动距离
            auto: true,//可选,默认false.自动上拉加载一次
            contentrefresh: "正在加载...",//可选，正在加载状态时，上拉加载控件上显示的标题内容
            contentnomore: '',//可选，请求完毕若没有更多数据时显示的提醒内容；
            callback: fenye //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
        }
    }
});


var cartData = getCartList() || {};
var endData = getCartList() || {};

fenye_options.dataName = 'goods_list';
fenye_options.originalData = originalData;
fenye_options.callback = function () {
    calculateTotalPrice();
    $('#all_checkbox').prop('checked', true);
    //点击取消或选中某个商品
    $('.checkBoxGoods').bind('click',function () {
        var id = parseInt(this.getAttribute('data-id'));
        //判断当前状态是选中还是取消选中
        if($(this).prop('checked')){
            console.log('选中')
            cartData[id].selected = true;
            endData[id] = cartData[id];
        }else {
            console.log('取消选中')
            cartData[id].selected = false;
            delete endData[id];
        }
        var checkedCount = 0;
        var allCount = 0;
        $('input[name="cart_id"]').each(function () {
            allCount++;
            if (!$(this).prop('checked')) {
                checkedCount++;
            }
        });
        if(checkedCount >0 && checkedCount <= allCount){
            $('#all_checkbox').prop('checked', false);
        }else {
            $('#all_checkbox').prop('checked', true);
        }

        console.log(endData)
        console.log(cartData)
        calculateTotalPrice();
    })


    //购买数量，减
    mui('.value-box').on('tap', '.minus', function () {
        var sPrents = $(this).parents(".cart-litemw-cnt");
        var goods_id = sPrents.attr('id');
        cartData[goods_id]['goods_num'] -= 1;
        if (cartData[goods_id]['goods_num'] <= 0) {
            // delCart(goods_id);
            // $("#" + goods_id).hide();
            cartData[goods_id]['goods_num'] = 1;
        }
        endData[goods_id]['goods_num'] = cartData[goods_id]['goods_num'];
        sPrents.find('.buy-num').val(cartData[goods_id]['goods_num']);
        addCart(cartData[goods_id],1);
        calculateTotalPrice();
    });
    //购买数量加
    mui('.value-box').on('tap', '.add', function () {
        var sPrents = $(this).parents(".cart-litemw-cnt");
        var goods_id = sPrents.attr('id');
        cartData[goods_id]['goods_num'] += 1;
        endData[goods_id]['goods_num'] = cartData[goods_id]['goods_num'];
        sPrents.find('.buy-num').val(cartData[goods_id]['goods_num']);
        addCart(cartData[goods_id],1);
        calculateTotalPrice();
    });
    mui('.goods-del').on('tap', 'a', function () {
        var cart_id = $(this).parent().attr('cart_id');
        mui.confirm('', '确认删除吗 ?', ['是', '否'], function (e) {
            if (e.index == 0) {
                delCart(cart_id);
                $("#" + cart_id).remove();
                delete endData[cart_id];
                calculateTotalPrice();
                var newCartData = getCartList() || {};
                var num = Object.keys(newCartData).length;
                if (num <= 0) {
                    $(fenye_options.domNode).empty();
                    html = '<div class="no_data" style="align-content: center;height: '+fenye_options.scrollHeight+';padding-top: 50%;text-align: center;font-size: 20px;color: lightgray;background-color: #f5f5f5">空空如也</div>';
                    $(fenye_options.domNode).append(html);
                }
            }
        })
    });
    $(".no_data").css('background-color','#f5f5f5');
};

// 所有全选
$("#all_checkbox").click(function () {
    $('.nctouch-cart-container').find('input[name="cart_id"]').prop('checked', $(this).prop('checked'));
    if ($(this).prop('checked')) {
        //选中
        endData = getCartList() || {};
    }else {
        //取消选中
        endData = {};
    }
    calculateTotalPrice();
});


function calculateTotalPrice(id) {
    var totalPrice = parseFloat("0.00");
    $('.cart-litemw-cnt').each(function () {
        if ($(this).find('input[name="cart_id"]').prop('checked')) {
            totalPrice += parseFloat($(this).find('.goods-price').find('em').html()) * parseInt($(this).find('.value-box').find('input').val());
        }
    });
    $(".total-money").find('em').html(totalPrice.toFixed(2));
    check_button(id);
    return true;
}

function check_button(id) {
    var _has = false
    $('input[name="cart_id"]').each(function () {
        if ($(this).prop('checked')) {
            _has = true;
        }
    });
    if (_has) {
        $('.check-out').addClass('ok');
    } else {
        $('.check-out').removeClass('ok');
    }
}

//去结算
mui('.check-out').on('tap', 'a', function () {
    if (!$(this).parent().hasClass('ok')) {
        return false;
    }
    /*var newCartData = getCartList() || {};*/
    var num = Object.keys(endData).length;
    if (num <= 0) {
        clearCart();
        redirect('index.html');
        return false;
    } else {
        setCache('pay-order',endData);
        flag = true;
        redirect('pay-order.html');
    }
});